'use strict';
const HTM = require('./utils').html;
const db = require("../coSqlite3");
const fs = require('fs');

exports.InitDB=function*(req) {
    const dataSql = "\
        drop table if exists book;\
        drop table if exists reader;\
        drop table if exists record;\
        \
        create table book (\
            bookID               varchar(30) not null,\
            bookName             varchar(30) not null,\
            bookPub              varchar(30),\
            bookDate             date,\
            bookAuthor           varchar(20),\
            bookMem              varchar(30),\
            bookCnt              int not null,\
            primary key (bookID)\
        );\
        create table reader(\
            readerID             bigint not null,\
            readerName           varchar(10),\
            readerSex            bool,\
            readerDept           varchar(10),\
            readerGrade          int,\
            primary key (readerID)\
        );\
        create table record(\
            recordID             bigint not null,\
            recordReaderID       bigint, \
            recordBookID         bigint, \
            borrowTime           datetime, \
            returnTime           datetime, \
            oughtReturnTime      datetime, \
            primary key (recordID)\
        );\
    ";
    let res;
    try {
        let dataArr = dataSql.toString().split(';');
        // 去除最后的空行
        dataArr.length = dataArr.length - 1;
        for (let query of dataArr) {
            if (query) {
                query += ';';
                yield db.execSQL(query);
            }
        }
        res = "初始化数据库成功！";
    } catch (err) {
        res = "数据库初始化失败！错误：" + err;
    }
    
    return HTM.begin + "<div id='result' style='display:none'>0</div>" + res + HTM.end;

};